﻿using System;
using System.Collections.Generic;
using System.Xml;
using System.Xml.Serialization;
using System.Text;
using System.IO;

namespace SerialUtilities
{
    public static class SerialUtil
    {
        public static string Serialize(Type objectType, object obj, bool useCDATA)
        {
            XmlSerializer s = new XmlSerializer(objectType);
            StringBuilder sb = new StringBuilder();
            StringWriter writer = new StringWriter(sb);
            s.Serialize(writer, obj);

            if (useCDATA)
            {
                XmlDocument doc = new XmlDocument();
                XmlCDataSection cdata = doc.CreateCDataSection(sb.ToString());
                return cdata.OuterXml;
            }

            return sb.ToString();
        }

        public static object Deserialize(Type objectType, string serialData, bool useCDATA)
        {
            string encasedData = String.Empty;

            if (useCDATA)
            {
                XmlDocument doc = new XmlDocument();
                XmlCDataSection cdata = doc.CreateCDataSection(serialData);
                encasedData = cdata.Data;
            }
            else
            {
                encasedData = serialData;
            }
            
            XmlSerializer s = new XmlSerializer(objectType);
            StringReader reader = new StringReader(encasedData);
            return s.Deserialize(reader);
        }

    }
}
